import requests,cv2
import json,base64,os
import numpy as np
from PIL import Image, ImageDraw, ImageFont
def base64str2mat(base64str):
    data = bytes(base64str, encoding='utf8')
    img_data = base64.b64decode(data)
    img_data = np.asarray(bytearray(img_data), dtype="uint8")
    image = cv2.imdecode(img_data, cv2.IMREAD_COLOR)
    return image

def mat2base64str(image):
    data = base64.b64encode(cv2.imencode('.jpg', image)[1]).decode()
    return data






#测是ocr_key接口
def test_ocr_key(keys,filename):
    with open(filename, 'rb') as f:
        content = base64.b64encode(f.read()).decode()
    #keys = ['颜色(COLOR)', '透明度(TMD)']
    r = requests.post('http://192.168.3.34:8080/ocr_key', data=json.dumps({'keys': keys, 'file': content}),
                      headers={'content-type': 'application/json'})
    return r.json()

#测试ocr_detail接口
def test_ocr_detail(filename):

    with open(filename, 'rb') as f:
        content = base64.b64encode(f.read()).decode()
    r = requests.post('http://192.168.3.34:8080/ocr_detail', data=json.dumps({'file': content}),
                      headers={'content-type': 'application/json'})

    error = r.json().get('error')
    if error is not None:
        return None

    words_result_num = r.json()['words_result_num']
    words_result = r.json()['words_result']
    raw_image = r.json()['image_raw']


    mat_image = base64str2mat(raw_image)
    pil_image = Image.fromarray(mat_image)
    font = ImageFont.truetype("msyh.ttc", 20)
    draw = ImageDraw.Draw(pil_image)

    for index in range(words_result_num):

        location = words_result[index]['location']
        xmin = location['xmin']
        ymin = location['ymin']
        xmax = location['xmax']
        ymax = location['ymax']
        word = words_result[index]['words']
        draw.rectangle((xmin, ymin, xmax, ymax), outline='red')
        draw.text((xmax, ymin), word, (0, 0, 255), font)
    # frame_pil.save("2_1.jpg")
    return  cv2.cvtColor(np.asarray(pil_image), cv2.COLOR_RGB2BGR)

def test_ocr_reqData(keys,filename):
    with open('1.jpg', 'rb') as f:
        content = base64.b64encode(f.read()).decode()
    reqData = [{'text':'颜色(COLOR)',"id":"","value":""},{ 'text':'透明度(TMD)'}]
    r = requests.post('http://192.168.3.34:8080/ocr_key1', data=json.dumps({'reqData': reqData, 'file': content}),
                      headers={'content-type': 'application/json'})
    print(r.json())

if __name__=="__main__":
    # dir1 = 'testdir'
    # dir2 = 'resultdir'
    # test_images = os.listdir(dir1)
    # for imagename in test_images:
    #     image = test_ocr_detail(os.path.join(dir1,imagename))
    #     if image is not None:
    #         cv2.imwrite(os.path.join(dir2,imagename),image)
    #test_ocr_reqData('','')
    dir_txt = 'sheets_txt'
    dir_img = 'sheets_img'
    dir_res  = 'sheets_res'
    files = os.listdir(dir_txt)
    imgs = os.listdir(dir_img)
    for filename in files:
        print(filename)
        imagename = filename.split('.')[0]+'.jpg'
        with open(os.path.join(dir_txt,filename),'r') as f:
            lines = f.readlines()
        lines = [line.strip() for line in lines]

        ret = test_ocr_key(lines,os.path.join(dir_img,imagename))
        print(ret)
        #ret  = test_ocr_detail(os.path.join(dir_img,imagename))
        #cv2.imwrite(imagename,ret)
